﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Web.UI.WebControls;
using TuyennvLibrary.ServerApi.Models;
using TuyennvLibrary.Utl;
using TuyennvLibrary.ServerApi.Controllers;

namespace ServerApi.administrator
{
    public partial class SmsClassManager : BasePage
    {
        SMSProcessClassModel smsClassModel = new SMSProcessClassModel();
        PartnerSMSModel partnerModel = new PartnerSMSModel();
        public int stt = 1;
        public string title = "Thêm class xử lý MO mới";
        List<FileInfo> filesdll = new List<FileInfo>();
        public int count = 0;
        protected new void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            if (!IsPostBack)
            {
                loadFileDlls();
                loadClassScript();
                LoadPartner();
                LoadPartnerSearch();
                loadTypeServiceid();
                loadServiceid();
                loadTypeServiceidSearch();
                loadServiceidSearch();
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    int id = int.Parse(Request["id"]);
                    loadinfo(id);
                    title = "Cập nhật class xử lý MO";
                }
                Search(1);
            }
        }
        public void loadFileDlls()
        {
            filesdll = TuyennvLibrary.ServerApi.Util.ApiUtilities.getFiles(Server.MapPath("/FileDLL/"), new string[] { ".dll" });
            foreach (FileInfo f in filesdll)
            {
                ddlFileDll.Items.Add(new ListItem { Text = f.Name, Value = f.Name });
            }
            ddlFileDll.Items.Insert(0, new ListItem { Text = "TuyennvLibrary.dll", Value = "" });
        }
        public void loadClassScript()
        {
            List<string> list = new List<string>();
            List<string> temp = new List<string>();
            if (ddlFileDll.Text == "")
            {
                temp = TuyennvLibrary.ServerApi.Util.ApiUtilities.GetClassesSMS();
            }
            else
            {
                temp = TuyennvLibrary.ServerApi.Util.ApiUtilities.GetClassesSMS(Assembly.LoadFile(Server.MapPath("/FileDLL/" + ddlFileDll.Text)));
            }
            if (temp.Count > 0)
                list.AddRange(temp);

            ddlClassScript.DataSource = list;
            ddlClassScript.DataBind();
        }
        private void loadinfo(int id)
        {
            SMSProcessClass obj = smsClassModel.GetByID(id);
            txtCommand.Text = obj.command_code;
            txtSubCode.Text = obj.subcodes;
            ddlPartner.Text = obj.partner.ToString();
            ddlPartnerSearch.Text = obj.partner.ToString();
            chkStatus.Checked = (obj.status == 1) ? true : false;
            ddlFileDll.Text = obj.file_dll;
            txtDeveloper.Text = obj.developer;
            loadTypeServiceid();
            loadTypeServiceidSearch();
            ddlTypeServiceIdSearch.Text = convertServiceIdToX(obj.short_code);
            ddlTypeServiceid.Text = convertServiceIdToX(obj.short_code);

            loadServiceid();
            
            loadServiceidSearch();
            ddlServiceIdSearch.Text = obj.short_code;
            ddlServiceid.Text = obj.short_code;
            loadClassScript();
            ddlClassScript.Text = obj.class_proccess;
        }
        private string convertServiceIdToX(string serviceid)
        {
            return serviceid[0] + "x" + serviceid.Substring(2);
        }
        public string getLinkTest(int Partnerid, int id)
        {
            SMSProcessClass objSms = smsClassModel.GetByID(id);
            PartnerSMS obj = (new PartnerSMSModel()).GetByID(Partnerid);
            string pageTest = "GetPartnerSMS.aspx?dev=true&partner=" + obj.id + "&";
            string request = string.Format("{0}{1}={2}&{3}={4}&{5}=01689942158",
                (!string.IsNullOrEmpty(obj.param_commandcode)) ? obj.param_commandcode + "=" + objSms.command_code + "&" : "",
                obj.param_message,
                objSms.command_code,
                obj.param_serviceid,
                objSms.short_code,
                obj.param_userid);
            return Config.domain + "/" + pageTest + request;
        }
        public void Search(int page)
        {
            int partner = int.Parse(ddlPartnerSearch.Text);
            int pagesize = 50;
            smsClassModel.page = page;
            smsClassModel.pagesize = pagesize;
            stt = (page - 1) * pagesize + 1;
            DataTable dt = smsClassModel.Search(partner, ddlServiceIdSearch.Text, txtCommandSearch.Text, txtDeveloperSearch.Text);
            GrvListAcc.DataSource = dt;
            GrvListAcc.DataBind();
            pager1.ItemCount = smsClassModel.Count;
            count = smsClassModel.Count;
            pager1.CurrentIndex = page;
            pager1.PageSize = pagesize;
        }
        public void LoadPartnerSearch()
        {
            DataTable dt = partnerModel.GetListAll();
            ddlPartnerSearch.DataSource = dt;
            ddlPartnerSearch.DataTextField = "name";
            ddlPartnerSearch.DataValueField = "id";
            ddlPartnerSearch.DataBind();
            ddlPartnerSearch.Items.Insert(0, new ListItem { Text = "--Tất cả--", Value = "0" });
        }
        public void LoadPartner()
        {
            DataTable dt = partnerModel.GetListAll();
            ddlPartner.DataSource = dt;
            ddlPartner.DataTextField = "name";
            ddlPartner.DataValueField = "id";
            ddlPartner.DataBind();

            ddlPartnerSearch.DataSource = dt;
            ddlPartnerSearch.DataTextField = "name";
            ddlPartnerSearch.DataValueField = "id";
            ddlPartnerSearch.DataBind();
            //ddlPartner.Items.Insert(0, new ListItem { Text = "Bluesea", Value = "0" });
        }
        //public void loadServiceidSearch()
        //{
        //    ddlServiceIdSearch.Items.Clear();
        //    if (ddlServiceIdSearch.Text != "0")
        //    {
        //        PartnerSMS partner = new PartnerSMS();
        //        partner = partnerModel.GetByID(int.Parse(ddlPartnerSearch.Text));

        //        for (int i = 0; i < 8; i++)
        //        {
        //            ddlServiceIdSearch.Items.Add(new ListItem { Text = partner.serviceid.Replace("x", i.ToString()), Value = partner.serviceid.Replace("x", i.ToString()) });
        //        }
        //    }
        //    ddlServiceIdSearch.Items.Insert(0, new ListItem { Text = "--Tất cả--", Value = "0" });
        //}
        public void loadTypeServiceidSearch()
        {
            PartnerSMS partner = new PartnerSMS();
            if (ddlPartner.Text != "0")
            {
                partner = partnerModel.GetByID(int.Parse(ddlPartner.Text));
            }
            else
            {
                partner.id = 0;
                partner.name = "BlueSea";
                partner.name_unsign = "bluesea";
                partner.serviceid = "8x77";
                partner.status = 1;
            }
            ddlTypeServiceIdSearch.Items.Clear();
            string[] arrServiceId = partner.serviceid.Split(',');
            foreach (string serviceid in arrServiceId)
            {
                if (!string.IsNullOrEmpty(serviceid))
                {
                    ddlTypeServiceIdSearch.Items.Add(new ListItem { Text = serviceid, Value = serviceid });
                }
            }
        }
        public void loadServiceidSearch()
        {
            ddlServiceIdSearch.Items.Clear();
            string typeServiceId = ddlTypeServiceIdSearch.Text;
            for (int i = 0; i < 8; i++)
            {

                ddlServiceIdSearch.Items.Add(new ListItem { Text = typeServiceId.Replace("x", i.ToString()), Value = typeServiceId.Replace("x", i.ToString()) });
            }
            ddlServiceIdSearch.Items.Insert(0, new ListItem { Text = "--Tất cả--", Value = "0" });
        }
        public void loadTypeServiceid()
        {
            PartnerSMS partner = new PartnerSMS();
            if (ddlPartner.Text != "0")
            {
                partner = partnerModel.GetByID(int.Parse(ddlPartner.Text));
            }
            else
            {
                partner.id = 0;
                partner.name = "BlueSea";
                partner.name_unsign = "bluesea";
                partner.serviceid = "8x77";
                partner.status = 1;
            }
            ddlTypeServiceid.Items.Clear();
            string[] arrServiceId = partner.serviceid.Split(',');
            foreach (string serviceid in arrServiceId)
            {
                if (!string.IsNullOrEmpty(serviceid))
                {
                    ddlTypeServiceid.Items.Add(new ListItem { Text = serviceid, Value = serviceid });
                }
            }
        }
        public void loadServiceid()
        {
            ddlServiceid.Items.Clear();
            string typeServiceId = ddlTypeServiceid.Text;
            for (int i = 0; i < 8; i++)
            {

                ddlServiceid.Items.Add(new ListItem { Text = typeServiceId.Replace("x", i.ToString()), Value = typeServiceId.Replace("x", i.ToString()) });
            }
        }
        protected void LbtnAccept_Click(object sender, EventArgs e)
        {
            try
            {
                SMSProcessClass obj = new SMSProcessClass();
                obj.command_code = txtCommand.Text.Trim();
                obj.short_code = ddlServiceid.Text.Trim();
                obj.subcodes = txtSubCode.Text.Trim();
                obj.class_proccess = ddlClassScript.Text.Trim();
                obj.partner = int.Parse(ddlPartner.Text);
                obj.status = (chkStatus.Checked) ? 1 : 0;
                obj.developer = txtDeveloper.Text.Trim();

                //if (fileUploadDll != null && fileUploadDll.HasFile)
                //{
                //    obj.file_dll = Utilities.UploadFile(fileUploadDll, new string[] { ".dll" }, "FileDLL/", Server);
                //}
                //else
                obj.file_dll = ddlFileDll.Text;
               
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    obj.id = int.Parse(Request["id"]);
                    if (smsClassModel.Update(obj))
                    {
                        Utilities.Alert(Page, this.GetType(), "Đã cập nhật class xử lý MO thành công");
                        Response.Redirect("SmsClass.aspx");
                    }
                }
                else
                {
                    DataTable dt = smsClassModel.GetListBy(new string[] { SMSProcessClass.COLUMN_SHORT_CODE, SMSProcessClass.COLUMN_COMMAND_CODE, SMSProcessClass.COLUMN_SUBCODES }, new object[] { obj.short_code, obj.command_code, obj.subcodes }, SMSProcessClass.COLUMN_SUBCODES);
                    if (dt.Rows.Count > 0)
                    {
                        throw new Exception("Mã này đã được tạo");
                    }
                    if (smsClassModel.Insert(obj))
                    {
                        Utilities.Alert(Page, this.GetType(), "Đã thêm mới class xử lý MO thành công");
                    }
                }
                Search(1);
            }
            catch (Exception ex)
            {
                Utilities.Alert(Page, this.GetType(), ex.Message);
            }
        }

        protected void LbtnSearch_Click(object sender, EventArgs e)
        {
            Search(1);
        }

        protected void GrvListAcc_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton l = (LinkButton)e.Row.FindControl("lbtnDel");
                l.Attributes.Add("onclick", "javascript:return " +
                "confirm('Bạn có muốn xóa ứng dụng này không? " + "')");
            }
        }

        protected void GrvListAcc_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int id = int.Parse(GrvListAcc.DataKeys[e.RowIndex].Value.ToString());
            if (smsClassModel.Delete(id))
            {
                Search(1);
                Utilities.Alert(Page, this.GetType(), "Đã xóa command thành công");
            }
        }

        protected void ddlPartner_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadTypeServiceid();
            loadServiceid();
        }

        protected void ddlPartnerSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadTypeServiceidSearch();
            loadServiceidSearch();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Search(1);
        }

        protected void ddlFileDll_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadClassScript();
        }

        protected void btnViewDescriptionClass_Click(object sender, EventArgs e)
        {
            Response.Redirect("DescriptionClassManager.aspx?typeclass=2");
        }

        protected void ddlTypeServiceid_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadServiceid();
        }

        protected void ddlTypeServiceIdSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadServiceidSearch();
        }
        protected void pager1_Command(object sender, CommandEventArgs e)
        {
            int currnetPageIndx = Convert.ToInt32(e.CommandArgument);
            Search(currnetPageIndx);
        }
    }
}